package com.cashmama.market.api.application.controller.order.repay;

import com.alibaba.fastjson.JSON;
import com.cashmama.market.api.application.annos.SignIgnore;
import com.cashmama.market.api.application.annos.VisitorAccessible;
import com.cashmama.market.api.domain.enums.PayNotifyCodeEnum;
import com.cashmama.market.api.domain.service.OrderService;
import com.cashmama.market.api.domain.vo.order.repayment.RePayResultInfo;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: market-api
 * @description 还款通知
 * @author: frank
 * @create: 2019-12-19 21:22
 **/
@Controller
@RequestMapping("/order/notify")
public class NotifyController {

    private static final Logger LOGGER = LoggerFactory.getLogger(NotifyController.class);

    @Autowired
    private OrderService orderService;

    /**
     * 异步还款通知
     * @param request
     * @param response
     * @throws Exception
     */
    @SignIgnore
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @ResponseBody
    @VisitorAccessible
    public void repayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        LOGGER.info("进入支付异步通知数据接收处理");

        try {
            String reqStr = IOUtils.toString(request.getInputStream(), "utf-8");
            LOGGER.info("接收支付异步通知数据：【" + reqStr + "】");
            orderService.handlePayCallbackResult(reqStr);
        } catch (Exception e) {
            write(response, PayNotifyCodeEnum.FAILD);
            LOGGER.error("Pay Notify: 异步通知报文解析异常:", e);
            return;
        }
        write(response, PayNotifyCodeEnum.SUCCESS);
        LOGGER.info("Pay Notify: 支付异步通知数据接收处理成功");
    }



    private void write(HttpServletResponse response, PayNotifyCodeEnum payNotifyCodeEnum) throws Exception {

        RePayResultInfo payResponse = new RePayResultInfo();
        payResponse.setRetCode(payNotifyCodeEnum.getCode());
        payResponse.setRetMsg(payNotifyCodeEnum.getDesc());
        response.getWriter().write(JSON.toJSONString(payResponse));
        response.getWriter().flush();
    }
}
